import { Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'toHTML'})
export class ToHTMLPipe implements PipeTransform {
  transform(value: any): string {
    let json = JSON.parse(value);
    let htmlString: string = '';
    let prevId;
    let isEnd: boolean = true;
    for (let key in json) {
      if (json[key]['prevId'] === null) {
        htmlString += createHTMLString(key);
        prevId = json[key]['id'];
      }
    }
    while (true) {
      for (let key in json) {
        if (json[key]['prevId'] === prevId) {
          htmlString += createHTMLString(key);
          prevId = json[key]['id'];
          isEnd = false;
          break;
        }
      }
      if (isEnd) break;
      isEnd = true;
    }
    return htmlString;

    function createHTMLString(key) {
      let type = json[key]['type'];
      let node;
      let isCenter = json[key]['align'] ? 'zeditor-is-center' : '';
      switch (type) {
        case 'paragraph':
          node = `<p class="${isCenter}">${json[key]['content']}</p>`;
          break;
        case 'title':
          node = `<p class="zeditor-${json[key]['size']} ${isCenter}">${json[key]['content']}<p>`;
          break;
        case 'link':
          node = `<p class="${isCenter}"><a href="${json[key]['url']}">${json[key]['content']}</a></p>`;
          break;
        case 'importantParagraph':
          node = `<p class="${isCenter}"><b>${json[key]['content']}</b></p>`;
          break;
        case 'image':
          let describe = json[key]['describe'] ? json[key]['describe'] : '';
          let src = 'http://static.lessonplan.cn/'+json[key]['path'];
          node = `<span class="zeditor-img-box-span"><img src="${src}"><span class="z-img-desc">${describe}</span></span>`;
          break;
      }
      return node;
    }

  }
}
